
import os
import shutil
import sys
import time
import math
import json
import zipfile
from subprocess import run
import subprocess
# import thread
# import thread6
sys.path.append('../..')
import FileUtils
import ArrayUtils

curPath = os.getcwd()
print(curPath)

projectPath = os.path.abspath(os.path.join(os.path.dirname(curPath), os.pardir,os.pardir))
print(projectPath)

import platform
sysstr = platform.system()
print(platform)


#插入使用接口
def insertUseFunction():
	#插入函数调用 launchScene);
	code1 = FileUtils.readUtf8FileData(os.path.join(curPath,"main1.js"))
	mainCode = FileUtils.readUtf8FileData(os.path.join(projectPath,"build/wechatgame/main.js"))
	pos = mainCode.find("launchScene);\n")
	begin = mainCode[0:pos + 14]
	end = mainCode[pos+15:]
	finalStr = begin +"\n"+ code1 +"\n"+ end
	FileUtils.writeToUtf8File(os.path.join(projectPath,"build/wechatgame/main.js"),finalStr)

#插入函数
def insertFunction():
	#插入函数
	code2 = FileUtils.readUtf8FileData(os.path.join(curPath,"main2.js"))
	mainCode = FileUtils.readUtf8FileData(os.path.join(projectPath,"build/wechatgame/main.js"))
	keyStr = "window._CCSettings = undefined;\n"
	pos = mainCode.find(keyStr)
	begin = mainCode[0:pos + len(keyStr)]
	end = mainCode[pos+len(keyStr) + 1:]
	finalStr = begin +"\n"+ code2 +"\n"+ end
	FileUtils.writeToUtf8File(os.path.join(projectPath,"build/wechatgame/main.js"),finalStr)

#把主代码放到子包路径
def moveMainLogicCodeToSubPackageDir():
	logicCodeFilePath = os.path.join(projectPath,"build/wechatgame/src/scripts/main/index.js")
	logicCode = FileUtils.readUtf8FileData(logicCodeFilePath)
	#创建子包路径
	logicSubPackageDir = os.path.join(projectPath,"build/wechatgame/subpackages/MainLogicCode")
	FileUtils.makedirs(logicSubPackageDir)
	FileUtils.writeToUtf8File(os.path.join(logicSubPackageDir,"game.js"),logicCode)
	#清空原来的主逻辑代码文件
	FileUtils.writeToUtf8File(logicCodeFilePath,"")

#声明子包
def declareSubpackages():
	path = os.path.join(projectPath,"build/wechatgame/game.json")
	jsonData = FileUtils.readJsonFileData(path)
	insertJsonData = FileUtils.readJsonFileData(os.path.join(curPath,"game.json"))
	print("jsonData = ",jsonData)
	print("insertJsonData = ",insertJsonData)

	if(not ("subpackages" in jsonData)):
		jsonData["subpackages"] = []
		
	for val in jsonData["subpackages"]:
		if val["name"] == "MainLogicCode":
			return

	jsonData["subpackages"].append(insertJsonData)
	FileUtils.writeJsonToFile(path,jsonData)


if __name__ == "__main__":
	insertUseFunction()
	insertFunction()
	moveMainLogicCodeToSubPackageDir()
	declareSubpackages()
	pass



